//
//  HMComposeViewController.swift
//  新浪微博
//
//  Created by 饶鹏伟 on 16/4/16.
//  Copyright © 2016年 饶鹏伟. All rights reserved.
//

//点击视图上的六个按钮 跳转到的导航控制器的根控制器
import UIKit
import SnapKit
import SVProgressHUD

class HMComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //设置视图的背景颜色
        view.backgroundColor=UIColor.whiteColor()
        
        //设置视图界面
         setupUI()
        
        //注册键盘弹出和收起的通知 当键盘的位置改变 通知工具条位置也改变
        registerNotification()
        
    }
    
    //注册通知
    private func registerNotification(){
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
     
    }
    
   //实现通知的方法 当键盘frame将要改变的时候执行这个方法 参数里面有键盘改变位置后的位置信息
    @objc private func keyboardWillChange(n: NSNotification){
        
        //print(n)
        
        let userInfo=n.userInfo!
        
        //CGRect  是结构体  字典中不能够直接装结构体  -> 应该包装成 NSValue类型的对象
        let rect=(userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

        //当键盘弹出 修改底部工具条的约束 让其在键盘上方
        toolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(-ScreenHeight+rect.origin.y)
            
        }
        
        //在动画闭包中 执行父视图的layoutIfNeeded
        UIView.animateWithDuration(0.25) { () -> Void in
            //以动画的方式让工具条随着键盘的上方移动
            self.view.layoutIfNeeded()
        }
        
    }
    

    //设置UI界面
    private func setupUI(){
        
        //设置导航条
        setNavBar()
        
        //设置发送微博文本
        setTextView()
        
        //设置底部工具条
        setToolBar()
        
        //设置图片选择控制器视图
        setPictureSelector()
        
        //将toolbar移动到最顶层
        view.bringSubviewToFront(toolBar)
        
    }
    
    
  //关闭按钮的点击方法
    @objc private func close(){
        
       //移除当前控制器视图
       dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    
    
    
 //发送按钮点击方法
    @objc private func send(){
        
        print("发送")
        
     //判断是否登录 如果没有登录提示用户
        guard let token = HMUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else{
            
            SVProgressHUD.showErrorWithStatus("你暂未登录")
            
            return
        }
        
    //走到这 说明授权成功 登录了
        
        HMNetworkTools.shardTools.sendStatus(token, status: textView.text, imageList: pictureSelector.imageList) { (result, error) -> () in
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
            self.close()
        }
    }
    
    
  //底部工具条的按钮点击事件
    @objc private func selectPicture(){
        print("选择图片")
        //当点击选择图片按钮 弹出图片选择控制器的视图
        //跟新约束
         pictureSelector.view.snp_updateConstraints { (make) -> Void in
            
            make.height.equalTo(ScreenHeight/3*2)
        }
        
    }
    
    
    @objc private func selectEmoticon(){
        print("选择表情")
        
        
    }
    
    
    
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //取消textview成为第一响应者 当点击屏幕 键盘退出
        textView.resignFirstResponder()
    }
    
    
    
    //懒加载右边发送按钮
    private lazy var rightBarbuttonItem: UIBarButtonItem = {
        
        let btn=UIButton()
        
       //设置文字
        btn.setTitle("发送", forState: .Normal)
        //添加点击事件
        btn.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        
        //设置背景图片
       btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
       btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
       btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        
        //设置文字大小和按钮大小
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        //设置UIBarButtonItem的视图
        let barButtonItem = UIBarButtonItem(customView: btn)
        return barButtonItem
    }()
    

    //懒加载发送微博文本textView
    private lazy var textView: UITextView={
        
        let tv=UITextView()
        //设置文本的基本属性
        tv.font=UIFont.systemFontOfSize(18)
        tv.textColor=UIColor.darkGrayColor()
        tv.backgroundColor=UIColor(white: 0.9, alpha: 1)
        //允许垂直拖动
        tv.alwaysBounceVertical = true
        //当拖动textView的时候 键盘消失
        tv.keyboardDismissMode = .OnDrag
        
        //设置代理
        tv.delegate=self
        

        return tv
    }()

    //懒加载占位文本
    private lazy var placeHolderlabel: UILabel = UILabel(text: "听说下雨天音乐和辣条更配哦", textColor: UIColor.lightGrayColor(), fontSize: 18)
    
    //懒加载底部工具条
    private lazy var toolBar: UIToolbar=UIToolbar()
    
    //懒加载图片选择控制器
    private lazy var pictureSelector: HMPictureSelectorController=HMPictureSelectorController()
    
    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}






//设置UI界面的扩展
extension HMComposeViewController{
    
    //设置导航条
    private func setNavBar(){
        //左边关闭按钮
       navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        //右边发送按钮
       navigationItem.rightBarButtonItem=rightBarbuttonItem
        
        //一开始设置右边按钮不可交互
        navigationItem.rightBarButtonItem?.enabled=false
        
        //设置导航条中间自定义视图
        print(navigationItem.titleView)
        //设置自定义视图的大小
        let myView=UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        
        //设置自定义视图上面的两个label
        let titleLabel=UILabel(text: "发布微博", textColor: UIColor.darkGrayColor(), fontSize: 18)
        let nameLabel=UILabel(text: HMUserAccountViewModel.sharedAccountViewModel.userAccount?.name ?? "", textColor: UIColor.lightGrayColor(), fontSize: 15)
        //把两个label添加到视图上
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            
           make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
            
            
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
            
            
        }
        //赋值
        navigationItem.titleView=myView
    }
    
    
    
    //设置发布微博文本
    private func setTextView(){
        //添加
        view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeHolderlabel)
        //设置约束
        placeHolderlabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    

    //设置底部工具条
    private func setToolBar(){
        //添加子视图 
        view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            //工具条默认的高度 44 不用设置高度
            make.left.right.bottom.equalTo(self.view)
            
        }
        
      //定义一个数组 用来储存底部工具条的按钮
        var items=[UIBarButtonItem]()
        
        //定义一个数组 储存按钮图片名称 和 按钮单击事件
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        

        //遍历数组 添加UIBarButtonItem到 UIBarButtonItem的数组中
        for item in itemSettings{
            
            if let actionName=item["actionName"]{
                
                //创建按钮
                let barButtonItem=UIBarButtonItem(imageName: item["imageName"], target: self, action: Selector(actionName))
                //把按钮添加到数组中
                items.append(barButtonItem)
                
            }
            
            //添加弹簧 让每个按钮分开
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
            
        }
        //移除最后一个
        items.removeLast()
        //设置底部工具条按钮为数组中的每个按钮
        toolBar.items=items
    }
    
    
    //设置图片选择控制器
    private func setPictureSelector(){
        
        //添加子视图控制器
        //以后如果要是使用控制器的视图之前 一定要提前持有该控制器  需要添加子视图的控制器 --> addChildViewController
        
        self.addChildViewController(pictureSelector)
        
        //添加子视图控制器的视图
        view.addSubview(pictureSelector.view)
        
        //设置约束
        pictureSelector.view.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(self.view)
            
            //设置初始高度为0
            make.height.equalTo(0)
        }
        
    }
    
    
}





//扩展 遵守textView的代理协议
extension HMComposeViewController: UITextViewDelegate{
    
    //实现代理方法
    func textViewDidChange(textView: UITextView) {
        
      //隐藏占位文本
      placeHolderlabel.hidden=textView.hasText()
        
      //打开发送交互
    navigationItem.rightBarButtonItem?.enabled = textView.hasText()
  
        
    }
    
    
    
}

